/** @jsxImportSource @emotion/react */
import * as React from "react";
import {InputLine, TextArea, Text, BlobInputList, Button, InputDatalist, useToast, Input, LineColumn
} from "customize-easy-ui-component";
import {
    InspectRecordLayout, InternalItemProps, useInputControlSure, useItemInputControl
} from "../../common/base";
import {EditStorageContext} from "../../StorageContext";
import {Each_ZdSetting, useTableEditor} from "../../hook/useRepTableEditor";
import {useMeasureInpFilter} from "../../common/hooks";
import {useUppyUpload} from "../../hook/useUppyUpload";
import {useMedia} from "use-media";
import {assertNamesUnique} from "../../common/eHelper";
import {现场结果选} from "../../escalator/sidewalkD/orcBase";


const 示图说明选: string[] | undefined=[ ];
const itemA测点位置=['示图说明','_FILE_S部位','检测结果'];
//只能上不变的：不然hook死循环
const defaultValCb= (par: { 检测结果?: any; })=>{
    const { 检测结果 }=par||{};
    if(!检测结果)   par.检测结果='所检项目未见异常，检测结果为1级。';
    return  par;
}
export const ResultDiagram=
  React.forwardRef((
    { children, show ,alone=true,redId,nestMd, repId}:InternalItemProps,  ref
  ) => {
      const {modified,setModified,} =React.useContext(EditStorageContext) as any;
      const [getInpFilter] = useMeasureInpFilter(null, itemA测点位置, defaultValCb);
      const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
      const onFinish = React.useCallback(async(upfile: any, del:boolean) => {
          onSure({...inp, '_FILE_S部位': upfile});
          !modified && setModified(true);
      }, [inp, modified,onSure,setModified]);
      const [uploadDom]=useUppyUpload({ repId:repId!,
           maxFile:10, onFinish, storeObj: inp?._FILE_S部位
      });

    return (
      <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show} redId={redId} nestMd={nestMd}
                           alone={alone}  label={'硬度检测结果-测点位置示意图'}>
          <InputLine label='测点位置示意图：'>
              <BlobInputList value={inp?.示图说明 || ''} rows={5} datalist={示图说明选}
                             onListChange={v => setInp({...inp, 示图说明: v || undefined}) } />
          </InputLine>
          测点位置示意图：
          {uploadDom}
         检测结果:
        <TextArea  value={inp?.检测结果 ||''} rows={8}
                 onChange={e => setInp({ ...inp, 检测结果: e.currentTarget.value||undefined}) } />
        {children}
      </InspectRecordLayout>
    );
} );

const render试材质={
    view:(orc:any, parentOrc:any)=>{
        return <Text css={{fontSize:'0.8rem'}}>试样材质/标准</Text>
    },
    text: '试样材质/标准',
};
const 部件名称选=['工艺管道' ];
const 仪器型号选=['MH660' ];
const 冲击装置选=['D' ];
const 试样材质选=['20' ];
const 热处理选=['原始状态' ];
const 耦合方式选=['刚性支承' ];
const 冲击方向选=['水平' ];
export const config测量仪 = [
    [['设备名称', '_$设备名称'],  ['部件名称', {n:'部件',t:'l',l:部件名称选}] ],
    [['测量仪器名称', '仪器名'],  ['测量仪器编号', '仪器编'] ],
    [['测量仪器型号',{n:'仪器型',t:'l',l:仪器型号选}], ['冲击装置类型',{n:'冲击',t:'l',l:冲击装置选}], ['检测日期',{n:'测日',t:'d'}] ],
    [[render试材质,{n:'材质',t:'l',l:试样材质选}], ['热处理状态',{n:'热处',t:'l',l:热处理选}], ['表面状态','表面'] ],
    [['试验温度', {n:'温度',u:'℃'}], ['耦合方式',{n:'耦合',t:'l',l:耦合方式选}], ['冲击方向', {n:'冲向',t:'l',l:冲击方向选}] ],
    //这底下若加 ['检测标准',{n:'环境',r:'ld'}] ，正式报告的列数与位置分配{1+2,1+2列数}不符合正常输出！，#只能另外拆开额外区分处理了。
    [['试验环境条件',{n:'环境',t:'l',l:现场结果选}] ]
];

const cb焊材= (inp: any, setInp: React.Dispatch<React.SetStateAction<any>>,name:string) => {
   return  <InputDatalist value={(inp?.[name]) || ''} datalist={['20','不明']}
                   onListChange={v => setInp({ ...inp, [name] :v || undefined}) } />
}
const cb分析结果= (inp: any, setInp: React.Dispatch<React.SetStateAction<any>>,name:string) => {
    return  <InputDatalist value={(inp?.[name]) || ''} datalist={['符合要求']}
                           onListChange={v => setInp({ ...inp, [name] :v || undefined}) } />
}

export const config评定=[['试验部位编号','n',90],['母材','M',60],['热影响区','R',60], ['焊缝','f',60] ] as Each_ZdSetting[];
const itemA评定=['评定表','单内编','单位','备注'];
const defaultV = (par: any) => {
    if(!par.备注)  par.备注='试验部位为硬度检测图中编号处的管件，1-26为法兰，27-32为弯头，33-50为弯管，51-50弯管，68-74为三通，75-77为异径管。';
    return  par;
};
export const EvaluationForm=
    React.forwardRef(({ children, show ,alone=true,refWidth,redId,nestMd}:InternalItemProps,  ref
    ) => {
        const [getInpFilter]=useMeasureInpFilter(null,itemA评定, defaultV);
        const {inp, setInp} = useItemInputControl({ ref,redId,nestMd });
        const headview=<Text variant="h5">
            硬度检测-分析结果表。
        </Text>;
        const [render部位汇总]=useTableEditor({inp, setInp,  headview,
            config: config评定, table: '评定表', column:8,  maxRf:5, });

        return (
            <InspectRecordLayout inp={inp} setInp={setInp}  getInpFilter={getInpFilter} show={show}  redId={redId} nestMd={nestMd}
                                 alone={alone}  label={'硬度检测-分析结果表'}>
                <LineColumn>
                    <InputLine label='单位内编号：'>
                        <BlobInputList value={inp?.单内编 || ''} rows={1} datalist={['见特性表']}
                                       onListChange={v => setInp({...inp, 单内编: v || undefined}) } />
                    </InputLine>
                    <InputLine  label='硬度值的单位:' >
                        <Input  value={inp?.单位 ||'HB'}  placeholder="结果表的表头"
                                onChange={e => setInp({ ...inp, 单位: e.currentTarget.value||undefined}) } />
                    </InputLine>
                </LineColumn>
                {render部位汇总}
                备注:
                <TextArea  value={inp?.备注 ||''} rows={8}
                           onChange={e => setInp({ ...inp, 备注: e.currentTarget.value||undefined}) } />
            </InspectRecordLayout>
        );
    } );


/**【开发测试用的】
 * */
export const EntranceSetup =
    React.forwardRef((
        {children, show, alone = true, repId, verId, rep}: InternalItemProps, ref
    ) => {
        const atPrint = useMedia('print');
        const toast = useToast();
        const checkName = true;      //开发测试完，改成=false, 测试时 REACT_APP_TEST 需设置， 开发模式的校对开关。
        const doCheckNames = React.useCallback((verId: string) => {
            //【承压更少项目】，那些属于公共模板目录的 分项报告的唯一性检查在对方自己检查看。
            const result = assertNamesUnique([{value: rep?.tzFields},
                {value: config测量仪, type:'esnt'},
                {value:[...itemA测点位置,...itemA评定 ]},
                 ]);
            toast({title: "完成！", subtitle: result ? "没发现冲突" : "测试开关没开", intent: "success"});
        }, [rep,toast]);
        const getInpFilter = React.useCallback((par: any) => {}, []);
        const {inp, setInp} = useItemInputControl({ref});
        if (atPrint) return null;
        else return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={'初始化本报告，默认值配置等'}>
                {checkName && <div>
                    <Text variant="h5">
                        构建开发模板时的工具：校验模板的存储name冲突；
                    </Text>
                    <Button intent='primary' onPress={() => {
                        doCheckNames(verId!);
                    }}>校验模板name唯一性</Button>
                </div>
                }
                <hr/>
            </InspectRecordLayout>
        );
    });

